package top.tenebrous.termbor.rpc.common.scan;


import cn.hutool.core.collection.CollUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.tenebrous.termbor.rpc.common.annotation.RpcReference;
import top.tenebrous.termbor.rpc.common.annotation.RpcService;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * @program: termbor-rpc
 * @description:
 * @author: yazhang6
 * @create: 2024-05-20 17:21
 **/
public class RpcReferenceScanner extends ClassScanner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RpcReferenceScanner.class);

    public static Map<String, Object> doScannerWithRpcReferenceAnnotationFilter(
        String host, int port, String scanPackage
//        RegistryService registryService
    ) throws Exception {
        Map<String, Object> handlerMap = new HashMap<>();
        List<String> classNameList = getClassNameList(scanPackage);
        if (CollUtil.isEmpty(classNameList)) {
            return handlerMap;
        }
        classNameList.stream().forEach((className) -> {
            try {
                Class<?> aClass = Class.forName(className);
                Field[] declaredFields = aClass.getDeclaredFields();

                Stream.of(declaredFields).forEach(field -> {
                    RpcReference rpcReference= field.getAnnotation(RpcReference.class);
                    if (Objects.nonNull(rpcReference)) {
                        // TOD 处理后续逻辑，将@RpcReference注解标注的接口引用代理对象，放入全局缓存中
                        LOGGER.info("当前标注了RpcReference注解的类实例名称:{}", aClass.getName());
                    }
                });

            }catch (Exception e) {
                LOGGER.error("扫描RpcReference注解类异常", e);
            }
        });
        return handlerMap;
    }
}
